import { v1 } from "uuid";

import request from "@/utils/requrest";

export async function upload(url, file, onProcess, uid = null) {
    const chunkSize = 3145728;
    const fileSize = file.size;
    let currentChunk = 0;
    const totalChunks = Math.ceil(fileSize / chunkSize);
    const formID = uid || v1();

    let result = {};

    for (; currentChunk < totalChunks; currentChunk++) {
        const offset = currentChunk * chunkSize;
        const currentChunkSize = (currentChunk + 1) * chunkSize;

        const fd = new FormData();

        fd.append("totalChunks", totalChunks);
        fd.append("offset", offset);

        fd.append("chunkBlock", file.slice(offset, currentChunkSize));
        fd.append("chunkID", currentChunk);

        fd.append("fileID", formID);
        fd.append("fileName", file.name);
        fd.append("fileSize", fileSize);

        const { data } = await request({
            method: "POST",
            url: url,
            data: fd,
        });
        result = data;

        onProcess &&
            onProcess(parseInt((currentChunk / totalChunks) * 100), fd);
    }

    return result;
}

export function subscribeUpload(uid) {
    let sse = new EventSource("/api/file/subscribe/"+uid);
    sse.onmessage = function (e) {
        if (e.data === "Ping") {
        } else if (e.data === "Recycle") {
            sse.close();
        } else {
            location.reload();
        }
    };
}
